package es_example;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.avg.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import com.alibaba.fastjson.JSONObject;

import es_example.MyObj;

public class Main {

	public static void main(String[] args) {
		System.out.println("es example");
		TransportClient client = get_client();
		if (client != null) {

			new_man_datas(client);
			query_json_object(client);
			agg_avg(client);
			agg_max(client);
			agg_min(client);
			close_es(client);
		}
	}

	public static TransportClient get_client() {
		// 设置集群名称
		Settings mysettings = org.elasticsearch.common.settings.Settings
				.builder().put("cluster.name", "elasticsearch").build();
		// 创建client
		try {
			TransportClient client = new PreBuiltTransportClient(mysettings)
					.addTransportAddress(new InetSocketTransportAddress(
							InetAddress.getByName("127.0.0.1"), 9300));

			// .addTransportAddress(new
			// InetSocketTransportAddress(InetAddress.getByName("host2"),
			// 9300));
			return client;

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		return null;

	}

	public static void query_single(TransportClient client) {
		String index = "example1";
		String type = "tp1";
		String id = "1";
		GetResponse getResponse = client.prepareGet() // 准备进行get操作，此时还有真正地执行get操作。（与直接get的区别）
				.setIndex(index) // 要查询的
				.setType(type).setId(id).get();
		String data = getResponse.getSourceAsString();
		System.out.println("data:" + data);
	}

	// query multi docs
	public static void query_multi(TransportClient client) {

		// 设置查询条件
		QueryBuilder queryBuilder = QueryBuilders.termQuery("name", "hello");

		SearchResponse response = client.prepareSearch("example1")
				.setQuery(queryBuilder).execute().actionGet();

		for (SearchHit hit : response.getHits().getHits()) {
			System.out.println("---->>hit.getId(): " + hit.getId());
			if (hit.getFields().containsKey("age")) {

				System.out.println("field.age: "
						+ hit.getFields().get("age").getValue());
			}
			String data = hit.getSourceAsString();
			System.out.println("data:" + data);

		}

	}

	public static void query_json_object(TransportClient client) {
		System.out.println("query_json_object");


		// 设置查询条件
		QueryBuilder queryBuilder = QueryBuilders.termQuery("name", "hou");

		SearchResponse response = client.prepareSearch("example*")
				.setQuery(queryBuilder).execute().actionGet();

		for (SearchHit hit : response.getHits().getHits()) {
			System.out.println("---->>hit.getId(): " + hit.getId());
			MyObj obj = JSONObject.parseObject(hit.getSourceAsString(),
					MyObj.class);
			if (obj != null) {
				System.out.println("json object name field:" + obj.getName());
			}

		}

	}

	public static void agg_avg(TransportClient client) {
		System.out.println("agg_avg");
		// 设置查询条件
		QueryBuilder queryBuilder = QueryBuilders.termQuery("name", "hou");
		AvgAggregationBuilder aggBuilder = AggregationBuilders.avg("myage")
				.field("age");
		SearchResponse sr = client.prepareSearch().setQuery(queryBuilder)
				.addAggregation(aggBuilder).execute().actionGet();

		Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
		for (String key : aggMap.keySet()) {
			Avg aggr = (Avg) aggMap.get(key);
			System.out.println("key:" + key + ",value:" + aggr.getValue());
		}

	}

	public static void agg_max(TransportClient client) {
		System.out.println("agg_max");
		// 设置查询条件
		QueryBuilder queryBuilder = QueryBuilders.termQuery("name", "hou");
		MaxAggregationBuilder aggBuilder = AggregationBuilders.max("myage")
				.field("age");
		SearchResponse sr = client.prepareSearch().setQuery(queryBuilder)
				.addAggregation(aggBuilder).execute().actionGet();

		Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
		for (String key : aggMap.keySet()) {
			Max aggr = (Max) aggMap.get(key);
			System.out.println("key:" + key + ",value:" + aggr.getValue());
		}

	}
	
	public static void agg_min(TransportClient client) {
		System.out.println("agg_min");
		// 设置查询条件
		QueryBuilder queryBuilder = QueryBuilders.termQuery("name", "hou");
		MinAggregationBuilder aggBuilder = AggregationBuilders.min("myage")
				.field("age");
		SearchResponse sr = client.prepareSearch().setQuery(queryBuilder)
				.addAggregation(aggBuilder).execute().actionGet();

		Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
		for (String key : aggMap.keySet()) {
			Min aggr = (Min) aggMap.get(key);
			System.out.println("key:" + key + ",value:" + aggr.getValue());
		}

	}
	
	//新建文档
	public static void new_doc(TransportClient client){
		MyObj obj =new MyObj();
		obj.setName("new name");
		obj.setAge(101);
		
		String json = JSONObject.toJSONString(obj);
		
		IndexResponse response = client.prepareIndex("example1", "tp1", "fa")
		        .setSource(json).get();

	}

	public static void new_index(TransportClient client,String indexName) {
		client.admin().indices().prepareCreate(indexName).get();
		
	}
	
	
	// 批量创建人口分布表，包含姓名，城市，年龄三个字段，按照城市写到不同的索引，后面kibana使用
	public static void new_man_datas(TransportClient client) {
		insert_man(client,"1","Name A","NanJing",12);
		insert_man(client,"2","Name B","NanJing",33);
		insert_man(client,"3","Name C","NanJing",56);
		insert_man(client,"11","Name D","ShangHai",6);
		insert_man(client,"12","Name E","ShangHai",28);
		insert_man(client,"13","Name F","ShangHai",34);

	}
	
	public static void insert_man(TransportClient client,String id,String name,String city,double age) {
		MyObj obj = new MyObj();
		obj.setName(name);
		obj.setAge(age);
		obj.setCity(city);

		String json = JSONObject.toJSONString(obj);

		IndexResponse response = client.prepareIndex("city_"+city.toLowerCase(), "city_man", id)
				.setSource(json).get();

	}
		
	public static void close_es(TransportClient client) {
		client.close();
	}
}